//
//  ViewController.m
//  MLXJSBridge
//
//  Created by SY on 2019/1/31.
//  Copyright © 2019 shenyue. All rights reserved.
//

#import "ViewController.h"
#import "MLXJSBridge_WK.h"
#import "MLXJSBridge.h"
#import "Base64.h"
#import <JavaScriptCore/JavaScriptCore.h>
#define SuppressPerformSelectorLeakWarning(Stuff) \
do { \
_Pragma("clang diagnostic push") \
_Pragma("clang diagnostic ignored \"-Warc-performSelector-leaks\"") \
Stuff; \
_Pragma("clang diagnostic pop") \
} while (0)


#import <objc/runtime.h>

@interface ViewController ()<WKNavigationDelegate,WKUIDelegate,UIImagePickerControllerDelegate
,UINavigationControllerDelegate,UIWebViewDelegate>



@property (nonatomic, strong) UIWebView *webview;
@property (nonatomic, strong) WKWebView *webView;

@property (nonatomic, strong) MLXJSBridge_WK *bridge;
//@property (nonatomic, strong) MLXJSBridge *bridge;

@property (nonatomic, copy) MLXJSBCallback callback;

@property (nonatomic, strong) UIImagePickerController *cameraVC;

@property (nonatomic, strong) UIButton *nativeBtn;

@property(nonatomic,strong) NSString *jsCallback;

@end

@implementation ViewController


- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"MLXJSBridge_WK demo";
    
    self.bridge = [[MLXJSBridge_WK alloc] init];
    self.webView = [_bridge getBridgeWebView];
    self.webView.UIDelegate =self;
    self.webView.navigationDelegate = self;
    _webView.frame = CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height);
    [self.view addSubview:_webView];
//
//    _nativeBtn  = [[UIButton alloc] initWithFrame:CGRectMake((self.view.frame.size.width - 200)/2, self.view.frame.size.height - 50, 200, 20)];
//    [_nativeBtn setTitle:@"native btn" forState:UIControlStateNormal];
//    [_nativeBtn addTarget:self action:@selector(_nativeClick) forControlEvents:UIControlEventTouchUpInside];
//    [_nativeBtn setTitleColor:[UIColor blueColor] forState:UIControlStateNormal];
//    [self.view addSubview:_nativeBtn];
//    [self.view bringSubviewToFront:_nativeBtn];

    [self _initWebView];
    
    [self _initBridge];
    
    [self catchJsLog];
}
- (NSArray*)rangeOfSubString:(NSString*)subStr inString:(NSString*)string {
    NSMutableArray *rangeArray = [NSMutableArray array];
    NSString*string1 = [string stringByAppendingString:subStr];
    NSString *temp;
   for(int i =0; i < string.length; i ++) {
    temp = [string1 substringWithRange:NSMakeRange(i, subStr.length)];
    if ([temp isEqualToString:subStr]) {
      NSRange range = {i,subStr.length};
       [rangeArray addObject: [NSValue valueWithRange:range]];
        }
      }
   return rangeArray;
}
- (void)_initBridge {
//    self.bridge = [MLXJSBridge bridgeForWebView:_webview];
    
    _bridge.nameSpace = @"mlxapp";
    __weak typeof(self) weakself = self;
    [_bridge registerAction:@"useApp" handler:^(NSArray *params, MLXJSBCallback callback) {
        if (params.count == 0) {
            callback(@{@"msg":@"没有填写方法",@"success":@NO});
            return;
        }
        NSString *selectorStr = params[0];
        selectorStr = [selectorStr stringByAppendingString:@":"];
        SEL sel = NSSelectorFromString(selectorStr);
        if (sel == nil) {
             callback(@{@"msg":@"方法名有误",@"success":@NO});
            return;
        }
        if (![self respondsToSelector:sel]) {
            callback(@{@"msg":@"没有定义相关方法",@"success":@NO});
            return;
        }
        NSDictionary *jsonDic;
        if (params.count > 1) {
            id jsonnStr = params[1];
             NSError *error = nil;
            NSData *data = [jsonnStr dataUsingEncoding:NSUTF8StringEncoding];
            jsonDic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:&error];
            if (error) return;
            self.jsCallback = jsonDic[@"callback"];
        }
        if (callback) {
            weakself.callback = callback;
        }
        dispatch_async(dispatch_get_main_queue(), ^{
             [self performSelector:sel withObject:jsonDic];
        });
    }];
}
-(void)getToken:(id)dic{
    NSString *token =@"Bearer eyJhbGciOiJIUzUxMiJ9.eyJ1c2VyTG9naW5OYW1lIjoiMTc2MDY3MjEzMTUiLCJ1c2VySWQiOiIxMiIsImNsaWVudElkIjoiSU9TLVdBUCIsImV4cGlyYXRpb24iOjE1NTYyNjEwNjAzMjgsImNyZWF0ZWQiOjE1NTU2NTYyNjAzMjgsImFjY291bnRUeXBlIjoxLCJhdWQiOiJtbHgiLCJpc3MiOiJtbHgiLCJleHAiOjE1NTYyNjEwNjB9.2hsw2Vebj-Xh3YHNyaKEDS5Rf7Msd35TW5jqes9ieaA8tXODchB3MgCdq4YK7WHr3OW77RP7_1eyU2EZZpWJXQ";
    [self.bridge callAction:@"callBackByToken" param:token completionHandler:^(id  _Nullable data, NSError * _Nullable error) {
        NSLog(@"%@",data);
    }];
}
-(void)cameraClick:(NSDictionary *)jsonDic{
    UIImagePickerController *cameraVC = [[UIImagePickerController alloc] init];
    cameraVC.delegate = self;
    cameraVC.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    [self presentViewController:cameraVC animated:YES completion:nil];
}
- (void)_initWebView {
    [self.view sendSubviewToBack:self.webView];

//    if (@available(iOS 12.0, *)){
//        NSString *baseAgent = [self.webView valueForKey:@"applicationNameForUserAgent"];
//        NSString *userAgent = [NSString stringWithFormat:@"%@ MlxApp",baseAgent];
//        [self.webView setValue:userAgent forKey:@"applicationNameForUserAgent"];
//    }
//    [self.webView evaluateJavaScript:@"navigator.userAgent" completionHandler:^(id result, NSError *error) {
//        NSLog(@"userAgent:%@", result);
//        NSString *oldAgent = (NSString *)result;
//        if ([oldAgent rangeOfString:@"MlxApp"].location != NSNotFound) {
//            return ;
//        }
//        NSString *newAgent = [NSString stringWithFormat:@"%@ %@", oldAgent, @"MlxApp"];
//        NSDictionary *dictionary = [NSDictionary dictionaryWithObjectsAndKeys:newAgent, @"UserAgent", nil];
//        [[NSUserDefaults standardUserDefaults] registerDefaults:dictionary];
//        [[NSUserDefaults standardUserDefaults] synchronize];
//        if (@available(iOS 9.0, *)) {
//            [self.webView setCustomUserAgent:newAgent];
//        } else {
//            [self.webView setValue:newAgent forKey:@"applicationNameForUserAgent"];
//        }
//    }];
    
//        NSString *htmlPath = [[NSBundle mainBundle] pathForResource:@"test" ofType:@"html"];
//        NSString *content = [NSString stringWithContentsOfFile:htmlPath encoding:NSUTF8StringEncoding error:nil];
//        [self.webView loadHTMLString:content baseURL:nil];
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://devtest.mlxing.com/#/home/index"]];
//    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://devtest.mlxing.com/#/home/index"]
//                                        cachePolicy:NSURLRequestUseProtocolCachePolicy
//                                         timeoutInterval:10.f];
  
    [self.webView loadRequest:request];
}


- (void)catchJsLog{
//    JSContext *ctx = [self.webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];
//    ctx[@"console"][@"log"] = ^(JSValue * msg) {
//        NSLog(@"H5  log : %@", msg);
//    };
//    ctx[@"console"][@"warn"] = ^(JSValue * msg) {
//        NSLog(@"H5  warn : %@", msg);
//    };
//    ctx[@"console"][@"error"] = ^(JSValue * msg) {
//        NSLog(@"H5  error : %@", msg);
//    };
}
-(UIImagePickerController *)cameraVC{
    if (!_cameraVC) {
        _cameraVC = [[UIImagePickerController alloc] init];
        _cameraVC.delegate = self;
        _cameraVC.sourceType = UIImagePickerControllerSourceTypeCamera;
    }
    return _cameraVC;
}
- (void)_nativeClick {
    [_bridge callAction:@"nativeClick" param:@{@"msg":@"I am from native"}];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    if (!_webView.title) {
        [_webView reload];
    }
}
#pragma mark - WKUIDelegate
- (void)webView:(WKWebView *)webView runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(void))completionHandler {
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"提示" message:message?:@"" preferredStyle:UIAlertControllerStyleAlert];
    [alertController addAction:([UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        completionHandler();
    }])];
    [self presentViewController:alertController animated:YES completion:nil];
    
}
- (void)webView:(WKWebView *)webView runJavaScriptConfirmPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(BOOL))completionHandler{
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"提示" message:message?:@"" preferredStyle:UIAlertControllerStyleAlert];
    [alertController addAction:([UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        completionHandler(NO);
    }])];
    [alertController addAction:([UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        completionHandler(YES);
    }])];
    [self presentViewController:alertController animated:YES completion:nil];
}
- (void)webView:(WKWebView *)webView runJavaScriptTextInputPanelWithPrompt:(NSString *)prompt defaultText:(NSString *)defaultText initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(NSString * _Nullable))completionHandler{
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:prompt message:@"" preferredStyle:UIAlertControllerStyleAlert];
    [alertController addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
        textField.text = defaultText;
    }];
    [alertController addAction:([UIAlertAction actionWithTitle:@"完成" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        completionHandler(alertController.textFields[0].text?:@"");
    }])];
    
    [self presentViewController:alertController animated:YES completion:nil];
}

#pragma mark - UIImagePickerControllerDelegate
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info {
    if ([[info objectForKey:UIImagePickerControllerMediaType] isEqualToString:@"public.image"]) {
        [picker dismissViewControllerAnimated:YES completion:nil];
        UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
        NSData *imageData = UIImageJPEGRepresentation(image,1) ;
        if (imageData.length > 500000) {
            CGFloat ratio = 500000.0/imageData.length;
            imageData = UIImageJPEGRepresentation(image,ratio) ;
        }
        NSString *base64 = [imageData base64EncodedString];
        NSString *source = [NSString stringWithFormat:@"data:image/jpeg;base64,%@", base64];
        NSArray *soureArr = @[source];
        NSDictionary *value = @{@"data":soureArr,
                                @"msg":@"",
                                @"success":@YES
                                };
        if(self.callback) {
            self.callback(value);
        }
        if (self.jsCallback) {
            [_bridge callAction:self.jsCallback param:value completionHandler:nil];
        }
        
    }
}

- (void)dealloc {
    NSLog(@"===========wk dealoc============");
}

//页面加载完成之后调用
- (void)webView:(WKWebView *)webView didFinishNavigation:(null_unspecified WKNavigation *)navigation{
    
    NSLog(@"");
    [self.webView evaluateJavaScript:@"navigator.userAgent" completionHandler:^(id result, NSError *error) {
        NSLog(@"new_userAgent:%@", result);
    }];
}
- (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(null_unspecified WKNavigation *)navigation withError:(NSError *)error{
    NSLog(@"%@",error);
}
#pragma mark - WKNavigationDelegate
- (void)webViewWebContentProcessDidTerminate:(WKWebView *)webView {
    [webView reload];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}
@end
